# -*- coding: utf-8 -*-

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

def write_data(fname, data):
    with open(fname, "wb") as f:
        for line in data:
            f.write("{0}\n".format(line))

def load_gps_csv(filename, handler):
    header = ['id', 'time', 'x', 'y', 'angle', 'type', 'speed', 'pos', 'lane']
    with open(filename, "rb") as f:
        for line in f:
            elems = line.strip().split(',')
            for i, key in enumerate(header):
                if key == 'time':
                    elems[i] = int(float(elems[i]))
                if key in ['x', 'y', 'speed', 'pos']:
                    elems[i] = float(elems[i])
            handler.process(elems[:-1])
    print("parse gps file finished")

def load_network(filename):
    tree = ET.ElementTree(file=filename)
    edges = {}
    for child in tree.getroot():
        if child.tag == 'edge':
            edge_id = child.attrib['id']
            edge_info = {}
            if 'type' in child.attrib:
                edge_info.setdefault('type', child.attrib['type'])
            if 'priority' in child.attrib:
                edge_info.setdefault('priority', int(child.attrib['priority']))

            edge_info.setdefault('speed', float(child[0].attrib['speed']))
            edge_info.setdefault('length', float(child[0].attrib['length']))
            edges.setdefault(edge_id, edge_info)
    return edges

